<template>
  <div class="prize-management-container">
    <!-- 搜索区域 -->
    <div class="search-area">
      <el-form
        :inline="true"
        :model="searchForm"
        class="search-form"
      >
        <el-form-item label="奖品名称">
          <el-input
            v-model="searchForm.prizeName"
            placeholder="请输入奖品名称"
            clearable
            style="width: 180px"
          />
        </el-form-item>

        <el-form-item label="奖品类型">
          <el-select
            v-model="searchForm.prizeType"
            placeholder="请选择奖品类型"
            clearable
            style="width: 180px"
          >
            <el-option
              label="全部"
              value=""
            />
            <el-option
              label="积分"
              value="积分"
            />
            <el-option
              label="谢谢惠顾"
              value="谢谢惠顾"
            />
            <el-option
              label="自定义奖品"
              value="自定义奖品"
            />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            @click="handleSearch"
          >
            查询
          </el-button>
          <el-button @click="resetSearch">
            重置
          </el-button>
        </el-form-item>

        <el-form-item style="margin-left: 20px;">
          <el-button
            type="primary"
            @click="handleAdd"
          >
            <i class="el-icon-plus" /> 新增奖品
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格区域 -->
    <div class="table-container">
      <el-table
        :data="currentPageData"
        border
        style="width: 100%"
        :header-cell-style="{
          background: '#f5f7fa',
          color: '#606266',
          fontWeight: 'bold'
        }"
        :row-style="{height: '60px'}"
        empty-text="暂无奖品数据"
      >
        <!-- ID列 -->
        <el-table-column
          prop="id"
          label="ID"
          width="80"
          align="center"
          fixed="left"
        />

        <!-- 奖品名称列 -->
        <el-table-column
          prop="name"
          label="奖品名称"
          align="center"
        />

        <!-- 奖品类型列 -->
        <el-table-column
          prop="type"
          label="奖品类型"
          width="170"
          align="center"
        >
          <template #default="{row}">
            <el-tag
              :type="row.type === '积分' ? 'success' : row.type === '谢谢惠顾' ? 'danger' : 'warning'"
              size="medium"
            >
              {{ row.type }}
            </el-tag>
          </template>
        </el-table-column>

        <!-- 奖品图片列 - 优化后 -->
        <el-table-column
          label="奖品图片"
          width="170"
          align="center"
        >
          <template #default="{row}">
            <el-image
              v-if="row.image"
              style="width: 60px; height: 60px"
              :src="row.image"
              :preview-src-list="[row.image]"
              fit="cover"
              hide-on-click-modal
            >
              <div
                slot="error"
                class="image-slot"
              >
                <i class="el-icon-picture-outline" />
              </div>
            </el-image>
            <span v-else>-</span>
          </template>
        </el-table-column>

        <!-- 奖品数量列 -->
        <el-table-column
          prop="quantity"
          label="奖品数量"
          width="120"
          align="center"
        />

        <!-- 状态列 -->
        <el-table-column
          prop="status"
          label="状态"
          width="150"
          align="center"
        >
          <template #default="{row}">
            <el-tag :type="row.status === '正常' ? 'success' : 'danger'">
              {{ row.status }}
            </el-tag>
          </template>
        </el-table-column>

        <!-- 创建时间列 -->
        <el-table-column
          prop="createTime"
          label="创建时间"
          width="200"
          align="center"
        />

        <!-- 更新时间列 -->
        <el-table-column
          prop="updateTime"
          label="更新时间"
          width="200"
          align="center"
        />

        <!-- 操作列 -->
        <el-table-column
          label="操作"
          width="200"
          align="center"
          fixed="right"
        >
          <template #default="{row}">
            <el-button
              size="mini"
              @click="handleEdit(row)"
            >
              修改
            </el-button>
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页区域 -->
    <div class="pagination-area">
      <span class="total-records">共 {{ filteredPrizes.length }} 条记录</span>

      <el-pagination
        :current-page="pagination.currentPage"
        :page-size="pagination.pageSize"
        :total="filteredPrizes.length"
        layout="prev, pager, next"
        @current-change="handleCurrentChange"
      />

      <el-select
        v-model="pagination.pageSize"
        size="mini"
        style="width: 100px; margin: 0 10px"
        @change="handleSizeChange"
      >
        <el-option
          v-for="item in [10, 20, 50, 100]"
          :key="item"
          :label="`${item}条/页`"
          :value="item"
        />
      </el-select>

      <div class="page-jump">
        <span>前往</span>
        <el-input
          v-model.number="jumpPage"
          size="mini"
          style="width: 50px; margin: 0 5px"
          @keyup.enter.native="handleJumpPage"
        />
        <span>页</span>
      </div>
    </div>

    <!-- 新增/编辑奖品对话框 - 优化后 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="50%"
      :modal="false"
    >
      <el-form
        :model="prizeForm"
        label-width="100px"
      >
        <el-form-item label="奖品名称">
          <el-input
            v-model="prizeForm.name"
            placeholder="请输入奖品名称"
          />
        </el-form-item>
        <el-form-item label="奖品类型">
          <el-select
            v-model="prizeForm.type"
            placeholder="请选择奖品类型"
          >
            <el-option
              label="积分"
              value="积分"
            />
            <el-option
              label="谢谢惠顾"
              value="谢谢惠顾"
            />
            <el-option
              label="自定义奖品"
              value="自定义奖品"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="奖品图片">
          <div class="image-upload-container">
            <div class="image-preview-box">
              <el-image
                v-if="prizeForm.image"
                style="width: 120px; height: 120px"
                :src="prizeForm.image"
                fit="cover"
              >
                <div
                  slot="error"
                  class="image-slot"
                >
                  <i class="el-icon-picture-outline" />
                </div>
              </el-image>
              <div
                v-else
                class="empty-image-box"
              >
                <i class="el-icon-picture-outline" />
                <span>奖品图片预览</span>
              </div>
            </div>
            <div class="upload-actions">
              <el-upload
                action="#"
                :show-file-list="false"
                :before-upload="beforeUpload"
                :http-request="handleUpload"
              >
                <el-button
                  size="small"
                  type="primary"
                >
                  点击上传
                </el-button>
              </el-upload>
              <el-button
                v-if="prizeForm.image"
                size="small"
                type="danger"
                style="margin-top: 10px;"
                @click="prizeForm.image = ''"
              >
                移除图片
              </el-button>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="奖品数量">
          <el-input-number
            v-model="prizeForm.quantity"
            :min="0"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-switch
            v-model="prizeForm.status"
            active-value="正常"
            inactive-value="禁用"
          />
        </el-form-item>
      </el-form>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button
          type="primary"
          @click="submitPrize"
        >确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'PrizeManagement',
  data () {
    return {
      searchForm: {
        prizeName: '',
        prizeType: ''
      },
      pagination: {
        currentPage: 1,
        pageSize: 10
      },
      jumpPage: 1,
      dialogVisible: false,
      dialogTitle: '新增奖品',
      prizeForm: {
        id: '',
        name: '',
        type: '',
        image: '',
        quantity: 0,
        status: '正常',
        createTime: '',
        updateTime: ''
      },
      prizes: [
        {
          id: 1,
          name: '积分',
          type: '积分',
          image: '',
          quantity: 5,
          status: '正常',
          createTime: '2022-08-14 15:38:22',
          updateTime: '2022-08-14 15:38:26'
        },
        {
          id: 2,
          name: '谢谢惠顾',
          type: '谢谢惠顾',
          image: '',
          quantity: 0,
          status: '正常',
          createTime: '2022-08-14 16:15:05',
          updateTime: '2022-08-14 16:15:07'
        },
        {
          id: 3,
          name: '积分',
          type: '积分',
          image: '',
          quantity: 20,
          status: '正常',
          createTime: '2022-08-14 16:15:32',
          updateTime: '2022-08-14 16:15:35'
        },
        {
          id: 4,
          name: '红包',
          type: '红包',
          image: '',
          quantity: 6,
          status: '正常',
          createTime: '2022-08-14 16:16:02',
          updateTime: '2022-08-14 16:16:05'
        },
        {
          id: 5,
          name: '积分',
          type: '积分',
          image: '',
          quantity: 30,
          status: '正常',
          createTime: '2022-08-14 16:19:41',
          updateTime: '2022-08-14 16:19:44'
        },
        {
          id: 6,
          name: '积分',
          type: '积分',
          image: '',
          quantity: 45,
          status: '正常',
          createTime: '2022-08-14 16:20:11',
          updateTime: '2022-08-14 16:20:13'
        },
        {
          id: 7,
          name: '谢谢惠顾',
          type: '谢谢惠顾',
          image: '',
          quantity: 0,
          status: '正常',
          createTime: '2022-08-14 16:21:04',
          updateTime: '2022-08-14 16:21:06'
        },
        {
          id: 8,
          name: '蓝牙耳机',
          type: '自定义奖品',
          image: '',
          quantity: 1,
          status: '正常',
          createTime: '2022-08-14 16:21:09',
          updateTime: '2022-08-14 16:21:12'
        },
        {
          id: 9,
          name: '手机',
          type: '自定义奖品',
          image: '',
          quantity: 1,
          status: '正常',
          createTime: '2022-08-14 16:21:09',
          updateTime: '2022-08-14 16:21:12'
        }, {
          id: 10,
          name: '手表',
          type: '自定义奖品',
          image: '',
          quantity: 1,
          status: '正常',
          createTime: '2022-08-14 16:21:09',
          updateTime: '2022-08-14 16:21:12'
        }
      ],
      filteredPrizes: []
    }
  },
  computed: {
    currentPageData () {
      const start = (this.pagination.currentPage - 1) * this.pagination.pageSize
      const end = start + this.pagination.pageSize
      return this.filteredPrizes.slice(start, end)
    }
  },
  created () {
    this.filteredPrizes = [...this.prizes]
  },
  methods: {
    handleSearch () {
      this.pagination.currentPage = 1
      this.filteredPrizes = this.prizes.filter(prize => {
        if (this.searchForm.prizeName && !prize.name.includes(this.searchForm.prizeName)) {
          return false
        }
        if (this.searchForm.prizeType && prize.type !== this.searchForm.prizeType) {
          return false
        }
        return true
      })
    },
    resetSearch () {
      this.searchForm = {
        prizeName: '',
        prizeType: ''
      }
      this.pagination.currentPage = 1
      this.filteredPrizes = [...this.prizes]
    },
    handleSizeChange (val) {
      this.pagination.pageSize = val
      this.pagination.currentPage = 1
    },
    handleCurrentChange (val) {
      this.pagination.currentPage = val
    },
    handleJumpPage () {
      const page = parseInt(this.jumpPage)
      const maxPage = Math.ceil(this.filteredPrizes.length / this.pagination.pageSize)

      if (!isNaN(page) && page >= 1 && page <= maxPage) {
        this.pagination.currentPage = page
      } else {
        this.$message.warning(`请输入1-${maxPage}之间的页码`)
        this.jumpPage = this.pagination.currentPage
      }
    },
    handleAdd () {
      this.dialogTitle = '新增奖品'
      this.prizeForm = {
        id: '',
        name: '',
        type: '',
        image: '',
        quantity: 0,
        status: '正常',
        createTime: '',
        updateTime: ''
      }
      this.dialogVisible = true
    },
    handleEdit (row) {
      this.dialogTitle = '修改奖品'
      this.prizeForm = JSON.parse(JSON.stringify(row))
      this.dialogVisible = true
    },
    handleDelete (id) {
      this.$confirm('确定删除这条奖品记录吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.prizes = this.prizes.filter(item => item.id !== id)
        this.filteredPrizes = this.filteredPrizes.filter(item => item.id !== id)
        this.$message.success('删除成功')
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    // handleUploadSuccess (response, file) {
    //   // 模拟上传成功
    //   this.prizeForm.image = 'https://via.placeholder.com/100'
    //   this.$message.success('上传成功')
    // },
    submitPrize () {
      if (!this.prizeForm.name) {
        this.$message.warning('请输入奖品名称')
        return
      }
      if (!this.prizeForm.type) {
        this.$message.warning('请选择奖品类型')
        return
      }

      const now = new Date()
      const timeStr = now.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        hour12: false
      }).replace(/\//g, '-')

      if (this.prizeForm.id) {
        // 修改
        const index = this.prizes.findIndex(item => item.id === this.prizeForm.id)
        if (index !== -1) {
          this.prizes[index] = {
            ...this.prizeForm,
            updateTime: timeStr
          }
        }
      } else {
        // 新增
        const newId = this.prizes.length > 0 ? Math.max(...this.prizes.map(item => item.id)) + 1 : 1
        this.prizes.push({
          ...this.prizeForm,
          id: newId,
          createTime: timeStr,
          updateTime: timeStr
        })
      }

      this.dialogVisible = false
      this.filteredPrizes = [...this.prizes]
      this.$message.success('操作成功')
    },
    // 新增图片上传相关方法
    beforeUpload (file) {
      const isImage = file.type.includes('image/')
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isImage) {
        this.$message.error('只能上传图片文件!')
      }
      if (!isLt2M) {
        this.$message.error('图片大小不能超过2MB!')
      }

      return isImage && isLt2M
    },

    handleUpload ({ file }) {
      // 模拟上传过程
      return new Promise(resolve => {
        const reader = new FileReader()
        reader.onload = (e) => {
          this.prizeForm.image = e.target.result
          this.$message.success('上传成功')
          resolve()
        }
        reader.readAsDataURL(file)
      })
    }
  }
}
</script>

<style scoped>
.prize-management-container {
  padding: 20px;
  background: #fff;
  min-width: 1200px;
}

.search-area {
  margin-bottom: 20px;
  padding: 20px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.search-form {
  display: flex;
  align-items: center;
}

.search-form .el-form-item {
  margin-bottom: 0;
  margin-right: 15px;
}

.action-area {
  margin-bottom: 20px;
}

.table-container {
  margin-bottom: 20px;
}

/* 分页区域样式 */
.pagination-area {
  margin-top: 20px;
  display: flex;
  align-items: center;
  padding: 10px 20px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.total-records {
  font-size: 14px;
  color: #606266;
  margin-right: 15px;
}

.page-jump {
  display: flex;
  align-items: center;
  font-size: 14px;
  color: #606266;
}

.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #c0c4cc;
  font-size: 20px;
}

/* 响应式调整 */
@media (max-width: 1600px) {
  .prize-management-container {
    min-width: 100%;
    overflow-x: auto;
  }

  .search-form {
    flex-wrap: wrap;
  }

  .search-form .el-form-item {
    margin-bottom: 10px;
  }

  .pagination-area {
    flex-wrap: wrap;
    justify-content: center;
  }

  .total-records {
    width: 100%;
    text-align: center;
    margin-bottom: 10px;
  }
}

/* 新增图片上传区域样式 */
.image-upload-container {
  display: flex;
  align-items: center;
  gap: 20px;
}

.image-preview-box, .empty-image-box {
  width: 100px;
  height: 100px;
  border: 1px dashed #dcdfe6;
  border-radius: 4px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-color: #f5f7fa;
}

.empty-image-box i {
  font-size: 24px;
  color: #c0c4cc;
  margin-bottom: 8px;
}

.empty-image-box span {
  font-size: 12px;
  color: #909399;
}

.upload-btn {
  margin-left: 0;
}

.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #c0c4cc;
  font-size: 24px;
}

/* 新增样式 */
.image-upload-container {
  display: flex;
  align-items: flex-start;
  gap: 20px;
}

.image-preview-box, .empty-image-box {
  width: 120px;
  height: 120px;
  border: 1px dashed #dcdfe6;
  border-radius: 4px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-color: #f5f7fa;
}

.empty-image-box i {
  font-size: 28px;
  color: #c0c4cc;
  margin-bottom: 8px;
}

.empty-image-box span {
  font-size: 14px;
  color: #909399;
}

.upload-actions {
  display: flex;
  flex-direction: column;
}

.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #c0c4cc;
  font-size: 28px;
}
</style>
